<?php


namespace app\admin\controller;


use app\admin\model\AuthGroup;
use app\admin\model\FlowScheme;
use app\admin\model\Item;
use app\admin\model\News;
use app\BaseController;
use app\Request;
use fast\Tree;
use think\facade\View;

class Flow extends BaseController
{
    /**
     * @var \app\admin\model\Admin
     */
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];
    protected $group = [];
    protected $role_id;

    public function initialize()
    {
        parent::initialize();

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $this->role_id = $n['id'];
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[($n['name'])] = $temp;
            }
            $groupdata = $result;
        }
        $this->group = $groupdata;
    }

    //显示资源
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');
            $result = FlowScheme::paginate($limit, false, ['page' => $page])->toArray();
            return json(['code' => 200, 'msg' => '', 'total' => $result['total'], 'data' => $result['data']]);
        }
        return View::fetch();
    }

    //新增资源
    public function add(Request $request)
    {
        if ($request->isAjax()) {
            $data = $request->param();
            if (!empty($request->param('select'))) {
                $data['flowcanuser'] = $request->param('select');
            }
            $data['uid'] = $this->auth->id;
            unset($data['select']);
            $result = FlowScheme::create($data);
            if ($result) {
                return json(['code' => 200, 'url' => '', 'msg' => '添加成功！']);
            }
        }
        return View::fetch();
    }

    //流程图设计
    public function flowDesign(Request $request, $id)
    {
        $one = $this->work->FlowApi('GetFlowInfo', $id);
        if (!$one) {
            $this->error('未找到数据，请返回重试!');
        }
        if ($request->isAjax()) {

        }
        View::assign('one', $one);
        View::assign('process_data', $this->work->ProcessApi('All', $id));
        return View::fetch();
    }

    //新增步骤
    public function add_process(Request $request)
    {
        $flow_id = $request->param('flow_id');
        $one = $this->work->FlowApi('GetFlowInfo', $flow_id);
        if (!$one) {
            return json(['status' => 0, 'msg' => '添加失败,未找到流程', 'info' => '']);
        }
        return json($this->work->ProcessApi('ProcessAdd', $flow_id));
    }

    //清空步骤
    public function del_allprocess(Request $request)
    {
        return json($this->work->ProcessApi('ProcessDelAll', $request->param('flow_id')));
    }

    //双击删除步骤
    public function delete_process(Request $request)
    {
        return json($this->work->ProcessApi('ProcessDel', $request->param('flow_id'), $request->param('process_id')));
    }

    //保存布局
    public function save_canvas(Request $request)
    {
        return json($this->work->ProcessApi('ProcessLink', $request->param('flow_id'), $request->param('process_info')));
    }

    //单击处理属性
    public function attribute(Request $request, $id)
    {
        $info = $this->work->ProcessApi('ProcessAttView', $id);
        if ($request->isAjax()) {
            $data = $request->param();
            $admin_and_role = $request->param('select');
            $auto_person = $request->param('auto_person');
            if ($auto_person == 4) { //指定人员
                $data['auto_sponsor_ids'] = $request->param('select');
                $admin_and_role_arr = explode(',', $admin_and_role);
                $auth_name = \app\admin\model\Admin::field('nickname')->where('id', 'in', $admin_and_role_arr)->select();
                $str = [];
                foreach ($auth_name as $key => $value) {
                    $str[] = $value['nickname'];
                }
                $data['auto_role_ids'] = "";
                $data['auto_role_text'] = "";
                $data['auto_sponsor_text'] = implode(',', $str);
            } else { //指定角色
                $data['auto_role_ids'] = $request->param('select');
                $admin_and_role_arr = explode(',', $admin_and_role);
                $auth_name = AuthGroup::field('name')->where('id', 'in', $admin_and_role_arr)->select();
                $str = [];
                foreach ($auth_name as $key => $value) {
                    $str[] = $value['name'];
                }
                $data['auto_sponsor_ids'] = "";
                $data['auto_sponsor_text'] = "";
                $data['auto_role_text'] = implode(',', $str);
            }

            return json($this->work->ProcessApi('ProcessAttSave', $data['id'], $data));
        }
        View::assign('op', $info['show']);
        View::assign('one', $info['info']);
        View::assign('from', $info['from']);
        View::assign('process_to_list', $info['process_to_list']);
        View::assign('child_flow_list', $info['child_flow_list']);
        return View::fetch();
    }

    //监听select获取信息
    public function nodePersonnel(Request $request)
    {
        $title = $request->param('title');
        if ($request->isAjax()) {
            switch ($title) {
                case 'renyuan':
                    $result = \app\admin\model\Admin::where('status', '1')->select();
                    $data = []; //转换到对应的格式
                    foreach ($result as $k1 => $v1) {
                        $data[]['name'] = $v1['nickname'];
                        $data[$k1]['value'] = $v1['id'];

                    }
                    return json($data);
                    break;
                case 'juese':
                    $list = collection(AuthGroup::select())->toArray();
                    $groupList = [];
                    foreach ($list as $k => $v) {
                        $groupList[$v['id']] = $v;
                    }
                    $list = [];
                    foreach ($this->group as $k => $v) {
                        if (isset($groupList[$k])) {
                            $groupList[$k]['name'] = $v;
                            $list[] = $groupList[$k];
                        }
                    }
                    $data = []; //转换到对应的格式
                    foreach ($list as $k1 => $v1) {
                        $data[]['name'] = $v1['name'];
                        $data[$k1]['value'] = $v1['id'];

                    }
                    return json($data);
                    break;
                default:
                    break;
            }
        }
    }

    //流程管理员
    public function adminTree(Request $request)
    {
        if ($request->isAjax()) {
            $admin = \app\admin\model\Admin::where('id', 'in', $this->childrenAdminIds)->select();
            $data = []; //转换到对应的格式
            foreach ($admin as $k1 => $v1) {
                $data[]['name'] = $v1['nickname'];
                $data[$k1]['value'] = $v1['id'];

            }
            return json($data);
        }
    }

    //测试业务
    public function test(Request $request)
    {
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');
            $result = News::paginate($limit, false, ['page' => $page])->toArray();
            return json(['code' => 200, 'msg' => '', 'total' => $result['total'], 'data' => $result['data']]);
        }
        return View::fetch();
    }

    public function test_add(Request $request)
    {
        if ($request->isAjax()) {
            $data = $request->param();
            $data['uid'] = $this->auth->id;
            $data['add_time'] = time();
            News::create($data);
        }
        return View::fetch();
    }


    public function btn($wf_fid, $wf_type, $status)
    {

        $url = url("/index/wf/wfcheck/", ["wf_type" => $wf_type, "wf_title" => '2', 'wf_fid' => $wf_fid]);
        $url_star = url("/index/wf/wfstart/", ["wf_type" => $wf_type, "wf_title" => '2', 'wf_fid' => $wf_fid]);
        switch ($status) {
            case 0:
                return '<span class="btn  radius size-S" onclick=layer_show(\'发起工作流\',"' . $url_star . '","450","350")>发起工作流</span>';
                break;
            case 1:
                $st = 0;
                $user_name = '';
                $flowinfo = $this->work->workflowInfo($wf_fid, $wf_type, ['uid' => $this->auth->id, 'role' => $this->role_id]);

                if ($flowinfo != -1) {
                    if (!isset($flowinfo['status'])) {
                        return '<span class="btn btn-danger  radius size-S" onclick=javascript:alert("提示：当前流程故障，请联系管理员重置流程！")>Info:Flow Err</span>';
                    }
                    if ($flowinfo['sing_st'] == 0) {
                        $user = explode(",", $flowinfo['status']['sponsor_ids']);
                        $user_name = $flowinfo['status']['sponsor_text'];
                        if ($flowinfo['status']['auto_person'] == 3 || $flowinfo['status']['auto_person'] == 4 || $flowinfo['status']['auto_person'] == 6) {
                            if (in_array($this->auth->id, $user)) {
                                $st = 1;
                            }
                        }
                        if ($flowinfo['status']['auto_person'] == 5) {
                            if (in_array($this->role_id, $user)) {
                                $st = 1;
                            }
                        }
                    } else {
                        if ($flowinfo['sing_info']['uid'] == $this->auth->id) {
                            $st = 1;
                        } else {
                            $admin = \app\admin\model\Admin::find($flowinfo['sing_info']['uid']);
                            $user_name = $admin->nickname ?? $flowinfo['sing_info']['uid'];
                        }
                    }
                } else {
                    return '<span class="btn  radius size-S">无权限</span>';
                }
                if ($st == 1) {
                    $data = [
                        'url' => "flow/check",
                        'title' => '审核',
                        'class' =>'layui-btn-normal',
                        'username' => $user_name,
                        'step'=>'当前',
                        'lay'=>'approval'
                    ];
                    return json(['code' => 200, 'msg' => '', 'data' => $data]);

                } else {
                    $data = [
                        'title' => '无权限',
                        'class' =>'layui-btn-disabled',
                        'username' => $user_name,
                        'step'=>'步骤',
                        'lay'=>''
                    ];
                    return json(['code' => 200, 'msg' => '', 'data' => $data]);
                }

            case 100:
                echo '<span class="btn btn-primary" onclick=layer_show(\'代审\',"' . $url . '?sup=1","850","650")>代审</span>';
                break;
                break;
            default:
                return '';
        }
    }

    //状态
    public function status($status)
    {
        switch ($status)
        {
            case 0:
                return json(['code' => 200, 'msg' => '保存中', 'data' => ['class' =>'layui-btn-primary']]);
                break;
            case 1:
                return json(['code' => 200, 'msg' => '流程中', 'data' => ['class' =>'layui-btn-normal']]);
                break;
            case 2:
                return json(['code' => 200, 'msg' => '审核通过', 'data' => ['class' =>'layui-btn-warm']]);
                break;
            default: //-1
                return json(['code' => 200, 'msg' => '退回', 'data' => ['class' =>'layui-btn-danger']]);
        }
    }
    //审批页面
    public function approval_check(Request $request){
        $data = $request->param();
        if ($request->isAjax()){
            $data = $request->param();
            $flowinfo =  $this->work->workdoaction($data,$this->auth->id);
            if ($flowinfo['code'] == 0){
                return json(['code' => 200, 'url' => '', 'msg' => '成功！']);
            }
        }
        $result = $this->work->workflowInfo($data['wf_fid'],$data['wf_type'],['uid'=>$this->auth->id,'role'=>$this->role_id]);
        View::assign('info',$data);
        View::assign('flowinfo',$result);
        return View::fetch();

    }
    public function success_info(Request $request){
        if ($request->isAjax()){
            $data = $request->param();
            $result = $this->work->workflowInfo($data['wf_fid'],$data['wf_type'],['uid'=>$this->auth->id,'role'=>$this->role_id]);

            return $result['sing_st'];
        }
    }
    //日志
    public function wflogs($id,$wf_type,$type='html'){
        $logs = $this->work->FlowLog('logs',$id,$wf_type);
        return $logs[$type];
    }

    public function check_flow(Request $request){
        $data = $request->param();
        View::assign('info',$data);
        return View::fetch();
    }


    //删除流程图
    public function del(Request $request){
        $ids = $request->param('ids');
        if ($ids){
            $ids_arr = explode(',',$ids);
            foreach ($ids_arr as $key=>$value){
                $flow = FlowScheme::with('process')->find($value);
                $flow->together(['process'])->delete();
            }
        }
        return json(['code' => 200, 'url' => '', 'msg' => '删除成功！']);
    }
}